package ms.mall.service;

import com.alibaba.fastjson.JSONObject;
import ms.common.exception.BizException;
import ms.common.token.AesUtil;
import ms.common.token.SessionKey;
import ms.common.token.SessionKeyUtil;
import ms.common.util.req.HttpReqUtil;
import ms.common.util.string.ObjectTranslate;
import ms.common.util.string.StringUtil;
import ms.mall.bean.UserParamBean;
import ms.mall.config.Constant;
import ms.mall.config.ResponseCode;
import ms.mall.dao.UserDAO;
import ms.mall.entity.User;
import ms.mall.vo.UserParamVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: ms
 * File Name: UserService
 * Package Name: ms.shop.service
 * Date: 2018/6/4  14:20
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param code
     * @return
     */
    public UserParamVo sign(String code) {
        UserParamVo userParamVo = new UserParamVo();
        //向微信发送请求，返回json数据
        String msg = HttpReqUtil.sendGet(Constant.WX_LOGIN_URL, "appid="+ Constant.MINIAPPID + "&secret=" + Constant.MINISECRET + "&js_code=" + code + "&grant_type=authorization_code");
        if(StringUtil.isEmpty(msg)) {//没有结果返回
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "code错误");
        }

        //将微信的json数据转成map
        Map<String,Object> map = JSONObject.parseObject(msg, Map.class);

        //微信返回的错误信息
        if(map.containsKey("errcode")) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "code错误");
        }

        String openid = ObjectTranslate.getString(map.get("openid"));
        String session_key = ObjectTranslate.getString(map.get("session_key"));
        String unionid = ObjectTranslate.getString(map.get("unionid"));

        //sessionKey 加密
        SessionKey sessionKey = new SessionKey(session_key, openid, unionid);
        //获得给前端的数据
        String thirdSession = sessionKey.getThird_session();
        //放入缓存--redis
        Map<String,Object> users = redisTemplate.opsForHash().entries("ms-mall");
        Map<String,Object> userSessionKeys = redisTemplate.opsForHash().entries("user_session_key");
        if(StringUtil.isEmpty(users)) {
            users = new HashMap<>();
        }
        users.put(thirdSession, openid);
        userSessionKeys.put(thirdSession, session_key);
        redisTemplate.opsForHash().putAll("ms-mall", users);
        redisTemplate.opsForHash().putAll("user_session_key", userSessionKeys);
        //查询该用户是否存在
        User user = userDAO.selectByPrimaryKey(openid);

        userParamVo.setThirdSession(thirdSession);
        userParamVo.setIsNewUser(StringUtil.isEmpty(user));

        return userParamVo;
    }

    /**
     * 新增或更新用户信息
     * @param userParamBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public UserParamVo create(UserParamBean userParamBean) {
        UserParamVo userParamVo = new UserParamVo();
        User user = new User();

        Map<String,Object> userSessionKeys = redisTemplate.opsForHash().entries("user_session_key");
        String sessionKey = ObjectTranslate.getString(userSessionKeys.get(userParamBean.getSessionKey()));
        try {
            String result = AesUtil.decrypt(userParamBean.getEncryptedData(), sessionKey, userParamBean.getIv(), "UTF-8");
            if (null != result && result.length() > 0) {
                Map<String,Object> map = JSONObject.parseObject(result, Map.class);
                user.setOpenid(ObjectTranslate.getString(map.get("openId")));
                user.setNickName(ObjectTranslate.getString(map.get("nickName")));
                user.setImg(ObjectTranslate.getString(map.get("avatarUrl")));
                user.setUnionId(StringUtil.isEmpty(ObjectTranslate.getString(map.get("unionId")))?"":ObjectTranslate.getString(map.get("unionId")));
                user.setCreateTime(System.currentTimeMillis());
            }
        } catch (Exception e1) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "解析异常");
        }
        //查询该用户是否存在
        User currentUser = userDAO.selectByPrimaryKey(userParamBean.getOpenid());

        if(StringUtil.isEmpty(currentUser)) {//数据库里没有
            //注册
            userDAO.insert(user);
            userParamVo.setImg(user.getImg());
            userParamVo.setNickName(user.getNickName());
            userParamVo.setOpenid(user.getOpenid());
        } else {
            //更新信息
            userDAO.updateByPrimaryKeySelective(user);
            userParamVo.setImg(user.getImg());
            userParamVo.setNickName(user.getNickName());
            userParamVo.setOpenid(user.getOpenid());
        }
        return userParamVo;
    }
}
